package com.houger.ddd.common.config.kafka;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.CommonClientConfigs;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.config.SaslConfigs;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.config.KafkaListenerContainerFactory;
import org.springframework.kafka.core.*;
import org.springframework.kafka.listener.AbstractMessageListenerContainer;
import org.springframework.kafka.listener.ConcurrentMessageListenerContainer;
import org.springframework.kafka.listener.ContainerProperties;
import org.springframework.kafka.support.converter.BatchMessagingMessageConverter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 此类的描述是：
 *
 * @date 2019-01-15 21:09
 **/
@Slf4j
@Configuration
@EnableKafka
@EnableConfigurationProperties(KafkaProperties.class)
public class KafkaConfig {

    @Resource
    private KafkaProperties kafkaProperties;

    @Bean
    @ConditionalOnMissingBean
    public KafkaTemplate<String, String> kafkaTemplate() {
        return new KafkaTemplate<>(producerFactory(kafkaProperties.getBootstrapServers(), kafkaProperties.getProducer()));
    }

    private ProducerFactory<String, String> producerFactory(List<String> bootstrapServers, KafkaProducerProperties kafkaProducerProperties) {
        return new DefaultKafkaProducerFactory<>(producerConfigs(bootstrapServers, kafkaProducerProperties));
    }

    private Map<String, Object> producerConfigs(List<String> bootstrapServers, KafkaProducerProperties kafkaProducerProperties) {
        Map<String, Object> props = new HashMap<>();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        props.put(ProducerConfig.ACKS_CONFIG, kafkaProducerProperties.getAcks());
        props.put(ProducerConfig.RETRIES_CONFIG, kafkaProducerProperties.getRetries());
        props.put(ProducerConfig.LINGER_MS_CONFIG, kafkaProducerProperties.getLingerMs());
        props.put(ProducerConfig.BATCH_SIZE_CONFIG, kafkaProducerProperties.getBatchSize());
        props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, kafkaProducerProperties.getBufferMemory());
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        String userName = Objects.isNull(kafkaProducerProperties.getUsername()) ? kafkaProperties.getUsername() : kafkaProducerProperties.getUsername();
        String password = Objects.isNull(kafkaProducerProperties.getPassword()) ? kafkaProperties.getPassword() : kafkaProducerProperties.getPassword();
        configureProperties(props, userName, password);
        return props;
    }

    @Bean
    @ConditionalOnMissingBean
    public KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, String>> kafkaListenerContainerFactory() {

        return kafkaListenerContainerFactoryBuilder(kafkaProperties.getBootstrapServers(), kafkaProperties.getConsumer());
    }

    public KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, String>> kafkaListenerContainerFactoryBuilder(List<String> bootstrapServers,
                                                                                                                                  KafkaConsumerProperties kafkaConsumerProperties) {
        ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory(bootstrapServers, kafkaConsumerProperties));
        factory.setConcurrency(kafkaConsumerProperties.getConcurrency());
        //@KafkaListener 批量消费  每个批次数量在Kafka配置参数中设置ConsumerConfig.MAX_POLL_RECORDS_CONFIG
        factory.setBatchListener(true);
        factory.setMessageConverter(new BatchMessagingMessageConverter());
        factory.getContainerProperties().setPollTimeout(kafkaConsumerProperties.getPollTimeout());
        //设置提交偏移量的方式 当每一条记录被消费者监听器（ListenerConsumer）处理之后提交
        // 手动调用Acknowledgment.acknowledge()后立即提交
        factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL_IMMEDIATE);
        return factory;
    }


    private ConsumerFactory<String, String> consumerFactory(List<String> bootstrapServers, KafkaConsumerProperties kafkaConsumerProperties) {
        final DefaultKafkaConsumerFactory<String, String> factory = new DefaultKafkaConsumerFactory<>(consumerConfigs(bootstrapServers, kafkaConsumerProperties));

        return factory;
    }

    private Map<String, Object> consumerConfigs(List<String> bootstrapServers, KafkaConsumerProperties kafkaConsumerProperties) {
        Map<String, Object> propsMap = new HashMap<>(16);
        propsMap.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        propsMap.put(ConsumerConfig.GROUP_ID_CONFIG, kafkaConsumerProperties.getGroupId());
        propsMap.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, kafkaConsumerProperties.getEnableAutoCommit());
        propsMap.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, kafkaConsumerProperties.getAutoCommitInterval());
        propsMap.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, kafkaConsumerProperties.getSessionTimeout());
        propsMap.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        propsMap.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        propsMap.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, kafkaConsumerProperties.getAutoOffsetReset());
        propsMap.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, kafkaConsumerProperties.getMaxPollRecords());
        propsMap.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, kafkaConsumerProperties.getMaxPollInterval());
        String userName = Objects.isNull(kafkaConsumerProperties.getUsername()) ? kafkaProperties.getUsername() : kafkaConsumerProperties.getUsername();
        String password = Objects.isNull(kafkaConsumerProperties.getPassword()) ? kafkaProperties.getPassword() : kafkaConsumerProperties.getPassword();
        configureProperties(propsMap, userName, password);
        return propsMap;
    }

    private void configureProperties(Map<String, Object> props, String userName, String password) {
        if (Objects.nonNull(userName) && Objects.nonNull(password)) {
            createConf(userName, password);
            String jaasConfig = String.format("org.apache.kafka.common.security.plain.PlainLoginModule required username=%s password=%s", userName, password);
            props.put(SaslConfigs.SASL_JAAS_CONFIG, jaasConfig);
            props.put(SaslConfigs.SASL_MECHANISM, "PLAIN");
            props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SASL_PLAINTEXT");
        }else{
            System.clearProperty("java.security.auth.login.config");
        }
    }

    private void createConf(String name, String password) {
        String property = System.getProperty("java.security.auth.login.config","/Users/ruyi/Java/project/ddd-java/promotion/kafka_jaas.conf");
        File file = new File(property);
        if (file.exists()) {
            return;
        }
        try (FileOutputStream fis = new FileOutputStream(file)) {
            String conf = String.format("KafkaClient {\n" +
                    "   org.apache.kafka.common.security.plain.PlainLoginModule required\n" +
                    "   username=\"%s\"\n" +
                    "   password=\"%s\";\n" +
                    "   };\n", name, password);
            fis.write(conf.getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            log.error("", e);
            throw new RuntimeException(e.getMessage());
        }
    }
}